﻿//This file is included in the NumericTextBox control and automatically included in
//the parent page via the override of PreRender in NumericTextBox.vb.  See AssemblyInfo.vb.
//-RL 03/2009
//BEST WAY TO DEBUG IS to add debugger; statement to script below and RUN SOLUTION FROM THIS PAGE IN DEBUG MODE.  Will stop at debugger statement.


//Populate the textbox with the formatted numeric value.    
function extractNumber(obj, e, decimalPlaces, allowNegative, bNumberGrouping, bDollar) {
    var temp = obj.value;
    var carPos = carPos = doGetCaretPosition(obj);  //must get current caret position before we monkey around with the field. -RL 7/2009
    var curCommas = temp.split(',').length - 1; //must get current count of current # of commas before we monkey around with the field. -RL 7/2009

    // check for arrow and control keys
    if (window.event) { key = e.keyCode; isCtrl = window.event.ctrlKey }
    else if (e.which) { key = e.which; isCtrl = e.ctrlKey; }
    if (isCtrl) return true;
    if (key == 9 || key == 35 || key == 36 || key == 37 || key == 38 || key == 39 || key == 40 || key == 16 || key == 17) return true;    //tab, home, end, arrow keys, shift, ctrl

    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\\.?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);

    temp = FormatNumber(temp, bNumberGrouping, bDollar)

    if (reg0.test(temp)) {
        return true;
    }
    else {

        // first replace all non numbers
        var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
        var reg1 = new RegExp(reg1Str, 'g');
        temp = temp.replace(reg1, '');

        if (allowNegative) {    // replace extra negative
            var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
            var reg2 = /-/g;
            temp = temp.replace(reg2, '');
            if (hasNegative) temp = '-' + temp;
        }

        if (decimalPlaces != 0) {
            var reg3 = /\./g;
            var reg3Array = reg3.exec(temp);
            if (reg3Array != null) { // keep only first occurrence of . and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
                var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
                reg3Right = reg3Right.replace(reg3, '');
                reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
                temp = temp.substring(0, reg3Array.index) + '.' + reg3Right;
            }
        }

        //re-Format the number
        temp = FormatNumber(temp, bNumberGrouping, bDollar)
        obj.value = temp;

        //Set caret position
        var newCommas = temp.split(',').length - 1; //count of current # of commas        
        if (bDollar && temp.length == 2) carPos = 2;   //move the caret one more to the right if we have only $        
        carPos = carPos + (newCommas - curCommas);
        setCaretPosition(obj, carPos);
    }
}

function doGetCaretPosition(ctrl) {
    var CaretPos = 0;
    // IE Support
    if (document.selection) {

        ctrl.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length - SelLength;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;

    return (CaretPos);

}

function blockNonNumbers(obj, e, allowDecimal, allowNegative, bNumberGrouping, bDollar) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;

    if (window.event) { key = e.keyCode; isCtrl = window.event.ctrlKey }
    else if (e.which) { key = e.which; isCtrl = e.ctrlKey; }
    if (key == 9 || key == 37 || key == 38 || key == 39 || key == 40 || key == 16) return true; //Allow tab, arrow keys, Shift
    if (isNaN(key)) return true;
    keychar = String.fromCharCode(key);
        
    if (key == 8 || isCtrl) { return true; }  // check for backspace or delete, or if Ctrl was pressed
    if (bNumberGrouping == true) { if (key == 130) return true; } //allow comma if numbergrouping is allowed

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    return isFirstN || isFirstD || reg.test(keychar);
}


//Add Commas and $ to the number
function FormatNumber(num, bNumberGrouping, bDollar) {
    if (bNumberGrouping == true) {
        var re = /(-?\d+)(\d{3})/;
        while (re.test(num)) {
            num = num.replace(re, '$1,$2')
        }
        //replace any , to the right of the decimil -RL 7/2009
        var x = num.split('.');
        if (x[1] != undefined) {
            var RoD = x[1].replace(/,/g, '')
            num = x[0] + '.' + RoD;
        }
    }

    if (bDollar == true) {
        num.replace('$', '');
        num = '$' + num;
    }
    return num;
}

//Remove Commas
function decommafy(obj) {
    var re = /,/g;
    obj.value = obj.value.replace(re, '');
}

//Get the current caret position
function caretPos(ctrl) {
    var CaretPos = 0;
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
        return CaretPos
    }
}

//Set the caret position for editing
function setCaretPosition(ctrl, pos) {
    // IE Support
    if (document.selection) {
        //ie support
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
    else {
        //Firefox        
        ctrl.selectionStart = pos;
        ctrl.selectionEnd = pos;
        ctrl.focus();
    }
}

var msOrigionalValue = '';
function textbox_onfocus(e) {
    msOrigionalValue = e.value;

    //execute user defined onfocus code if defined
    if (e.onfocus1) eval(e.onfocus1);
}

function textbox_onblur(e) {
    if (msOrigionalValue != e.value) {
        if (e.onchange) {
            //On IE
            if (e.fireEvent) {
                e.fireEvent('onchange');
            }
            //On Gecko based browsers.  They seem to handle onchange just fine. -RL 7/2009
//            if (document.createEvent) {
//                var evt = document.createEvent('HTMLEvents');
//                if (evt.initEvent) {
//                    evt.initEvent('change', true, true);
//                }
//                if (e.dispatchEvent) {
//                    e.dispatchEvent(evt);
//                }
//            }
        }
    }

    //execute user defined onblur code if defined
    //http://www.alistapart.com/articles/scripttriggers/
    var ob1 = e.getAttribute('onblur1');    //Must use this syntax to get firefox and chome to work.
    if (ob1) eval(ob1);
}





